#!/bin/bash

LOG_PATH="logs/config_vrf.log"

# 解除vlan和vrf的绑定，并删除vlan和vrf
del_vlan() {
  id=$1
  sudo cat /proc/net/vlan/config | grep -w $id > /dev/null
  if [ $? -eq 0 ]; then
    sudo ip link set vlan$id nomaster >> $LOG_PATH 2>&1
    sudo ip link set vlan$id down >> $LOG_PATH 2>&1
    sudo ip link delete vlan$id type vlan >> $LOG_PATH 2>&1
  fi
  sudo ip vrf show | grep -w $id > /dev/null
  if [ $? -eq 0 ]; then
    sudo ip link set vrf$id down >> $LOG_PATH 2>&1
    sudo ip link delete vrf$id type vrf >> $LOG_PATH 2>&1
  fi
}

# 脚本运行起始位置
echo "============================= del_vlan_vrf start =============================" >> $LOG_PATH 2>&1

if (( $# < 1 )); then
  echo "failed"
  echo "need input vrfname[vrf101/all]"
  exit;
fi

# 处理输入参数，all表示删除所有vlan
if [ $1 == "all" ]; then
  echo "delete all vlan" >> $LOG_PATH 2>&1
  vlan_num=$((`sudo cat /proc/net/vlan/config | wc -l` - 2))
  while (( $vlan_num > 0 ))
  do
    vlan_id=`sudo cat /proc/net/vlan/config | awk "NR==3" | cut -d' ' -f1 | awk -F'vlan' '{print $2}'`
    # echo "del $vlan_name"
    del_vlan $vlan_id
    if [ $? -ne 0 ]; then
      echo "failed"
      echo "delete vlan$1 failed" >> $LOG_PATH 2>&1
      exit 1
    else
      echo "delete vlan$vlan_id success" >> $LOG_PATH 2>&1
    fi
    vlan_num=$((`sudo cat /proc/net/vlan/config | wc -l` - 2))
  done
else
  vrf_id=`echo $1 | awk -F'vrf' '{print $2}'`
  del_vlan $vrf_id
  if [ $? -ne 0 ]; then
    echo "failed"
    echo "delete vlan$vrf_id failed" >> $LOG_PATH 2>&1
    exit 1
  else
    echo "delete vlan$vrf_id success" >> $LOG_PATH 2>&1
  fi
fi
echo "success"
exit 0